package common

import (
	"fmt"
	"github.com/mjiulee/lego"
	"github.com/valyala/fasthttp"
)

type AppCtrlBaseInterface interface {
	InitApp(miniAppId int64) error
	Prepare(ctx *fasthttp.RequestCtx) error
	Finish(ctx *fasthttp.RequestCtx) error
	AppCtrlMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler
	CheckMiniAppId(miniAppId int64) bool
}

var _ AppCtrlBaseInterface = (*AppCtrlBase)(nil) //编译时检测是否实现了接口函数

type AppCtrlBase struct {
	AppCtrlBaseInterface

	MyMiniAppId int64
}

func (t *AppCtrlBase) InitApp(miniAppId int64) error {
	t.MyMiniAppId = miniAppId
	return nil
}

func (t * AppCtrlBase) DoInit() error {
	return nil
}

func (t * AppCtrlBase) Prepare(ctx *fasthttp.RequestCtx) error {
	return nil
}

func (t * AppCtrlBase) Finish(ctx *fasthttp.RequestCtx) error {
	return nil
}

func (t * AppCtrlBase) CheckMiniAppId(miniAppId int64) bool {
	if miniAppId != t.MyMiniAppId {
		return false //mini_app_id不匹配
	}

	return true
}

func (t * AppCtrlBase) AppCtrlMiddleware(next fasthttp.RequestHandler) fasthttp.RequestHandler {
	return func(ctx *fasthttp.RequestCtx) {
		ctxEx := lego.RequestCtxExtent{ctx}


		sessionData := GetSessionData(&ctxEx)
			if isMatch := t.CheckMiniAppId(sessionData.AppTokenWho.MiniAppId); !isMatch {
			ctxEx.ResponseWithStateCode200(1, fmt.Sprintf("appid check failed, expect id is %, but receive id is %d", t.MyMiniAppId, sessionData.AppTokenWho.MiniAppId))
			return
		}

		err := t.Prepare(ctx)
		if err != nil {
			ctxEx.ResponseWithStateCode200(1, err.Error())
			return
		}

		next(ctx)

		err = t.Finish(ctx)
		if err != nil {
			ctxEx.ResponseWithStateCode200(1, err.Error())
			return
		}
	}
}